package com.thot.timyag.config;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;

import java.util.HashMap;
import java.util.Map;

import com.thot.timyag.config.datasource.DatasourceSington;
import com.thot.timyag.config.properties.PersistenceProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.Database;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

/**
 * @author yangjf
 * @time 2019-07-01 10:37
 */
@Configuration
@ConditionalOnProperty(name = "thot.persistence.enable", havingValue = "true")
@EnableTransactionManagement
@EnableJpaRepositories(
        // repository包名
        basePackages = "com.thot.timyag.web.dao.repository",
        // 实体管理bean名称
        entityManagerFactoryRef = "thotEntityManagerFactory",
        // 事务管理bean名称
        transactionManagerRef = "thotTransactionManager"
)
@EnableConfigurationProperties({PersistenceProperties.class})
public class JpaConfigure {
    @Autowired(required = false)
    private PersistenceProperties persistenceProperties;

    @Autowired(required = false)
    private EntityManagerFactoryBuilder builder;

    /**===========下面配置JPA==============*/
    /**
     * 获取主库实体管理工厂对象
     * <p>
     *
     * @return 实体管理工厂对象
     */
    @Bean(name = "thotEntityManagerFactory")
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        if (null == builder) {
            HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
            adapter.setShowSql(true);
            adapter.setDatabase(Database.H2);
            adapter.setDatabasePlatform("org.hibernate.dialect.H2Dialect");
            this.builder = new EntityManagerFactoryBuilder(
                    adapter, new HashMap<>(),
                    null);
        }
        DatasourceSington.setPersistenceProperties(persistenceProperties);
        DataSource datasource = DatasourceSington.getDataSource();
        Map<String, Object> properties = new HashMap<>(4);
        properties.put("hibernate.naming.implicit-strategy", "org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy");
        properties.put("spring.jpa.hibernate.naming.physical-strategy", "org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl");

        return builder
                // 设置数据源
                .dataSource(datasource)
                .properties(properties)
                // 设置实体包名
                .packages("com.thot.timyag.web.dao.entity")
                // 设置持久化单元名，用于@PersistenceContext注解获取EntityManager时指定数据源
                .persistenceUnit("thotPersistenceUnit")
                .build();
    }

    /**
     * 获取实体管理对象
     *
     * @param factory 注入名为primaryEntityManagerFactory的bean
     * @return 实体管理对象
     */
    @Bean(name = "thotEntityManager")
    @ConditionalOnBean(name = "thotEntityManagerFactory")
    public EntityManager entityManager(@Qualifier("thotEntityManagerFactory") EntityManagerFactory factory) {
        return factory.createEntityManager();
    }

    /**
     * 获取主库事务管理对象
     *
     * @param factory 注入名为primaryEntityManagerFactory的bean
     * @return 事务管理对象
     */
    @Bean(name = "thotTransactionManager")
    @ConditionalOnBean(name = "thotEntityManagerFactory")
//    @ConditionalOnMissingBean
    public PlatformTransactionManager transactionManager(@Qualifier("thotEntityManagerFactory") EntityManagerFactory factory) {
        return new JpaTransactionManager(factory);
    }
}
